package com.guomei.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class HttpUtils {

    private static final OkHttpClient client;

    // 初始化OkHttpClient
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 发送GET请求
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应结果
     * @throws IOException 异常
     */
    public static String get(String url, Map<String, String> params) throws IOException {
        // 构建请求参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("GET请求失败: {} {}", response.code(), response.message());
                throw new IOException("请求失败: " + response);
            }

            ResponseBody body = response.body();
            return body != null ? body.string() : null;
        } catch (IOException e) {
            log.error("GET请求异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 发送POST表单请求
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应结果
     * @throws IOException 异常
     */
    public static String postForm(String url, Map<String, String> params) throws IOException {
        // 构建表单参数
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .post(formBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("POST请求失败: {} {}", response.code(), response.message());
                throw new IOException("请求失败: " + response);
            }

            ResponseBody body = response.body();
            return body != null ? body.string() : null;
        } catch (IOException e) {
            log.error("POST请求异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 发送POST JSON请求
     * @param url 请求URL
     * @param json 请求JSON字符串
     * @return 响应结果
     * @throws IOException 异常
     */
    public static String postJson(String url, String json) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, mediaType);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("POST JSON请求失败: {} {}", response.code(), response.message());
                throw new IOException("请求失败: " + response);
            }

            ResponseBody responseBody = response.body();
            return responseBody != null ? responseBody.string() : null;
        } catch (IOException e) {
            log.error("POST JSON请求异常: {}", e.getMessage(), e);
            throw e;
        }
    }
}
